from flask_restful import Resource, reqparse, marshal_with, inputs
from flask import current_app, jsonify
from ..models import Mission, User
from flask_jwt_extended import jwt_required, current_user
from .dto import mission_dto, application_dto
from .util import remove_none_fields
from ..error import InvalidUsage
from .mission_recommend import item_recommend

parser = reqparse.RequestParser()
parser.add_argument('type', type=str,
                    help='mission type')
parser.add_argument('title', type=str,
                    help='mission title')
parser.add_argument('description', type=str)
parser.add_argument('picture', type=str)
parser.add_argument('people', type=int)
parser.add_argument('credit_per_people', type=float)
parser.add_argument('deadline', type=inputs.datetime_from_iso8601)
parser.add_argument('picture', type=str)

parser.add_argument('page_size', type=int)
parser.add_argument('page_num', type=int)

parser.add_argument('searchType', type=str, location='args')
parser.add_argument('searchKeyword', type=str, location='args')


class MissionsService(Resource):
    @jwt_required()
    @marshal_with(mission_dto)
    def post(self):
        # current_app.logger.info("add mission bodys: {}".format(request.form))
        args = remove_none_fields(parser.parse_args())
        current_app.logger.info("add mission: {}".format(args))
        user = User.query_by_id(current_user.id)
        owed = User.owed_credit(current_user.id)
        current_app.logger.info(
            "user remained :{}, owed: {}".format(user.credit, owed))

        if user.credit < owed + args['credit_per_people'] * args['people']:
            raise InvalidUsage("积分不足以支付已发布任务及新发布任务", status_code=401)

        mission = Mission(**args, owner=user)
        mission.save()
        return mission

    @jwt_required()
    @marshal_with(mission_dto)
    def get(self):
        args = parser.parse_args()
        current_app.logger.info("search args {}".format(args))
        type = args['searchType']
        key_word = args['searchKeyword']
        # todo type强制搜索，keyword用推荐
        rs_mission_id_list = item_recommend(type, key_word, current_user.id)
        current_app.logger.info(
            "rs_mission_id_list, {}".format(rs_mission_id_list))
        return [Mission.query_by_id(id) for id in rs_mission_id_list]


class AppliedMissionsService(Resource):
    @jwt_required()
    @marshal_with(mission_dto)
    def get(self):
        return Mission.query_by_applier(current_user.id)


class MissionService(Resource):
    @jwt_required()
    @marshal_with(mission_dto)
    def get(self, mission_id):
        mission = Mission.query_by_id(mission_id)
        if mission is None:
            raise InvalidUsage('Mission not found', status_code=404)
        return mission

    @jwt_required()
    @marshal_with(mission_dto)
    def put(self, mission_id):
        args = remove_none_fields(parser.parse_args())
        mission = Mission.query_by_id(mission_id)
        if mission is None:
            raise InvalidUsage('Mission not found', status_code=404)
        if mission.owner_id != current_user.id:
            raise InvalidUsage('Current user is not owner', status_code=400)

        return Mission.update_by_id(mission_id, args)

    @jwt_required()
    def delete(self, mission_id):
        mission = Mission.query_by_id(mission_id)
        if mission is None:
            raise InvalidUsage('Mission not found', status_code=404)
        if mission.owner_id != current_user.id:
            raise InvalidUsage('Current user is not owner', status_code=400)

        # Mission.delete_mission(mission)
        Mission.update_by_id(mission_id, {'state': 3})
        return jsonify({'message': 'Mission deleted'})


class MissionApplicationService(Resource):
    @jwt_required()
    @marshal_with(application_dto)
    def get(self, mission_id):
        mission = Mission.query_by_id(mission_id)
        if mission is None:
            raise InvalidUsage('Mission not found', status_code=404)
        return mission.applications
